package com.automapper.criterion;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

public class SimpleExpression implements Criterion {

	private String columnName;
	private Object value;
	private String op;
	public SimpleExpression(String columnName, Object value, String op) {
		this.columnName = columnName;
		this.value = value;
		this.op = op;
	}
	
	@Override
	public String toSqlString() {
		StringBuilder sb = new StringBuilder();
		sb.append(columnName + " " + op + " ");
		if (value instanceof List) {
			String str = "#{%s[%d]}";
			List<Object> values = (List<Object>) value;
			List<Object> list = new ArrayList<>();
			for (int i = 0; i < values.size(); i++) {
				list.add(String.format(str, this.getParameterAliases(), i));
			}
			sb.append(" (").append(StringUtils.join(list, ",")).append(") ");
		} else {
			sb.append("#{" + this.getParameterAliases() + "}");
		}
		return sb.toString();
	}

	public String getParameterAliases() {
		String str = this.toString();
		return str.substring(str.lastIndexOf('.') + 1, str.length());
	}

	@Override
	public Object getValue() {
		return value;
	}

	@Override
	public Map<String, Object> getValues() {
		Map<String, Object> map = new HashMap<>();
		map.put(getParameterAliases(), value);
		return map;
	}

	@Override
	public List<String> getAliase() {
		List<String> list = new ArrayList<>();
		String aliase = StringUtils.substringBefore(columnName, ".");
		if (StringUtils.isBlank(aliase) || StringUtils.equals(aliase, columnName)) {
			return list;
		}
		list.add(aliase);
		return list;
	}
}
